const replaceFucn = require('./replaceFucn')
class ReplaceVueTemplate extends replaceFucn {

  constructor(props){
    super(props)
    this.replace()
  }

  // 替换标签内容中文
  replaceTagContent() {
    const matchReg = /(>)([^><]*[\u4e00-\u9fa5]+[^><]*)(<)/gim;
    this.content = this.content.replace(matchReg, (text,prev, match, after) => {
      // 判断是否是模板字符串
      const isTemplateReg = /({{)(\s*`[^`]*[\u4e00-\u9fa5]+[^`]*`\s*)(}})/gim;
      if (isTemplateReg.test(text)) {
        return text.replace(isTemplateReg, (_, prev, match, after) => {
          return `${prev}${this.replaceChinese(match,'')}${after}`
        });
      }else{
        return `${prev}{{${this.replaceChinese(match,'')}}}${after}`
      }
    });
    return this;
  }

  // 替换标签中的属性
  replaceRiskAttr() {
    const matchReg =
      /:?\w+=(['"`])(((?!\1)[\s\S])*[\u4e00-\u9fa5]+((?!\1)[\s\S])*)\1/gim;
    this.content = this.content.replace(matchReg, (text) => {
      let [prev, match] = text.split('=');
      let result = '';
      const suffix = match.substr(0, 1);
      // 判断是不是复杂属性，比如数组，对象 :a="{}" :a="[]"
      if (/(['"])[\[\{]((?!\1)[\s\S])*[\]\}](\1)/gim.test(match)) {
        let replaceReg =
          /(['`])((?!\1)[\s\S])*[\u4e00-\u9fa5]+((?!\1)[\s\S])*(\1)/gim;
        if (match.startsWith("'")) {
          replaceReg =
            /(["`])((?!\1)[\s\S])*[\u4e00-\u9fa5]+((?!\1)[\s\S])*(\1)/gim;
        }
        result = match.replace(replaceReg, (text) => {
          return this.replaceChinese(text, '', suffix === '"' ? "'" : '"');
        });
      } else {
        result = this.replaceChinese(match, suffix, suffix === '"' ? "'" : '"');
      }
      result = `${prev.includes(':') ? '' : ':'}${prev}=${result}`;
      return result;
    });
    return this;
  }

  replace() {
    this.replaceTagContent().replaceRiskAttr();
  }
}

module.exports = ReplaceVueTemplate;
